<?php
namespace Home\Controller;
use Think\Controller;

class OrderController extends CommonController {

    //订单列表
    public function index() {
        $state = I('get.state');
        $uid = session('user_id');
        $map['uid'] = $uid;

        switch($state){
            case "ncheck" ://审核
                $map2['a.uid'] = $uid;
                break;
            case "npay" : //未发货
                $map['is_pay'] = array('eq', -1);
                $map['status'] = array('neq', -1);
                break;
            case "is_d" ://待收货
                $map['is_deliver'] = 1;
                $map['status'] = array('neq' ,3);
                break;
            case "to_d" ://待发货
                $map['is_pay'] = array('eq', 1);
                $map['is_deliver'] = array('eq', -1);
                break;
            default : ;break;
        }

        //搜索(订单号)
        $search = trim(I('get.search'));
        if ( !empty($search) ) {
            ($state == 'ncheck') ? $map2['b.order_id'] = $search : $map['order_id'] = $search;
        }

        //订单列表
        if ($state == 'ncheck') {//审核
            $order = D('Admin/Order')->orderGoodThrough($map2,'0,3');
        } else {//全部,待付款,待发货,待收货
            $order = D('Admin/Order')->orderGood($map,'0,3');
        }

        $this->assign('search', $search);
        $this->assign('state', $state);
        $this->assign('order', $order);
        $this->display();
    }

    // 查询订单的运费
    public function freight()
    {
        $good_ida = I('post.good_id');
        $freight_id = I('post.freight_id');
        $address_id = I('post.address_id');
        $good_num  = I('post.num');
        $good_type = I('post.good_type');
        $good_idaarry = explode(",",$good_ida);
        $good_numarray = explode(",",$good_num);
        $good_typearray = explode(",",$good_type);

        $agentAddress = M('agentAddress')->where( array('address_id'=>$address_id) )->find();
        $express_area_name = M('expressAreaname')->where( array('area_name'=>$agentAddress['city'],'express_id'=>$freight_id) )->find();
        if(!$express_area_name){
            $express_area_name = M('expressAreaname')->where( array('area_name'=>$agentAddress['province'],'express_id'=>$freight_id) )->find();
        }
        $express_area = M('express_area')->where( array('id'=>$express_area_name['express_area_id']) )->find();
        if(!$express_area){
            $this->ajaxReturn(-1);
        }
        $is_agent = M("agent")->where("agent_id = %d" ,array(session("user_id")))->getField("is_agent");
        foreach($good_idaarry as $key=>$value) {

            // 查询商品的重量
            $good = M('good')->where(array('id' => $value))->find();
            // 商品是否包邮
            if($good['is_free'] == 1){
//                包邮就没有重量了
                $weight = 0 ;
            }else{
                // 该商品的品牌下，该用户层级是否包邮
                $rank_id = M('agent_brand')->where(array('agent_id'=>session('user_id'),'brand_id'=>$good['brand_id']))->getField('rank_id');
                $is_free = M('agent_rank')->where(array('rank_id'=>$rank_id))->getField('is_free');
                if($is_free == 1){
                    $weight = 0 ;
                }else{
                    $type = $good_typearray[$key];
                    $num = $good_numarray[$key];
                    // 计算重量
                    if($is_agent == 2){
                        $weight = $good['weight'] * $num;
                    }else{
                        if ($type == 1) {//如果是单件
                            $weight = $good['weight'] * $num;
                        } else {
                            $weight = $good['weight'] * $good['per_num'] * $num;
                        }
                    }
                }
            }
            $sum[$key]=$weight;
        }
        $weight_sum = ceil(array_sum($sum));
        if($weight_sum<=$express_area['standard']){
            $fright_prices = $express_area['standard']*$express_area['down_num'];
        }else{
            $up_fright = ($weight_sum - $express_area['standard'])*$express_area['up_num'];
            $down_fright = $express_area['standard']*$express_area['down_num'];
            $fright_prices = $up_fright + $down_fright;
        }
        $this->ajaxReturn($fright_prices);
    }

    //订单详情
    public function detail()
    {
        $good_ida = I('get.good_ida');
        $good_num = I('get.good_num');
        $count = I('get.count');
        $status = I('get.status');
        $good_aid = I('get.good_aid');

        $good_idaarry = explode(",",$good_ida);
        $good_numarray = explode(",",$good_num);
        $good_statusarray = explode(",",$status);

        //查询代理的层级
        $user_id = session('user_id');
        $agent = M('agent')->where( array('agent_id'=>$user_id) )->find();
        //可选快递
        $express = M('express')->where( array('state'=>1) )->order('id DESC')->select();

        foreach ($good_idaarry as $key=>$value){
        $good = D('Admin/Good')->relation(true)->where( array('id'=>$value) )->find();
        $new_rank_id = M('agentBrand')->where( array('brand_id'=>$good['brand_id'], 'agent_id'=>$user_id) )->getField('rank_id');
        $rankPrice = M('goodRankPrice')->where( array('good_id'=>$value, 'rank_id'=>$new_rank_id) )->find();
        if($good_numarray[$key]==0){
            $good_numarray[$key] = 1;
        };
        $good['good_num'] = $good_numarray[$key];
        $good['status'] = $good_statusarray[$key];
//            状态为1的时候为单件价格
        if($good_statusarray[$key] == 1){
            $good['comprice'] = $rankPrice['unit_amt'];
        }else if($good_statusarray[$key] == 2){
            $good['comprice'] = $rankPrice['batch_amt'];
        }else{
            $good['comprice'] = $good['price'];
        }
        $good['sum'] = $good['good_num']*$good['comprice'];
        $goods[$key] = $good;
    }
//        核对总数是否正确
        $all = 0;
        foreach ($goods as $gey=>$val){
            $all  = $all + $val['sum'];
        }
        if($all!=$count){
            $this->error("数据有误",U("GoodShopcart/shopcart"));
        };
        $pay_types = M("payment")->where("is_open = 1")->field("p_id,pay_code,p_name")->select();
        $this->assign("pay_types" ,$pay_types);
        //计算总件数
        $address = M("agent_address")->where("state = 0 AND agent_id = %d",array(session("user_id")))->select();
        $totalsum = array_sum($good_numarray);
        //print_r($goods);
        $this->assign('totalsum',$totalsum);
        $this->assign('address',$address);
        $this->assign('express', $express);
        $this->assign('agent', $agent);
        $this->assign('goods', $goods);
        $this->assign('count',$count);
        $this->assign('good_num',$good_num);
        $this->assign('good_ida',$good_ida);
        $this->assign('status',$status);
        $this->assign('good_aid',$good_aid);
        $this->display();
    }

    //用户确认下单
    public function order_confirm()
    {
        //订单信息
        $id = I('get.id');
        $uid = session('user_id');
        $order = D('Admin/order')->relation(true)->where( array('id'=>$id) )->find();

        //订单里面的商品
        $orderGood = D('Admin/OrderGood')->relation(true)->where( array('order_id'=>$order['id']) )->select();
        $brand_name = M('brand')->where( array('id'=>$orderGood[0]['brand_id']) )->getField('b_name');
        //是否为董事
        $res = top_rank($orderGood[0]['brand_id']);
        if ($res['agent_id'] == $uid) {
            $this->assign('is_director', 1);
        }
        //预存款
        $brand_money = M('agent')->where( array('agent_id'=>$uid) )->getField('money');

        //查询是否有代理此品牌
        $brand = M('agent_brand')->where( array('agent_id'=>$uid, 'brand_id'=>$orderGood[0]['brand_id']) )->find();

        //查询下单人订单的总金额
        $orderThrough = M('orderThrough')->where( array('order_id'=>$id, 'uid'=>$uid) )->find();

        //查询上级代理应该付的订单的金额
        $sum = top_order_price($id, $uid);

        //如果是微信支付类(没有代理此品牌和平台商品的话)
        if (empty($brand) || $orderGood[0]['type'] == 2) {
            $this->assign('real_pay', 1);
        }
        // 查询所有支付方式
        $payments = M("payment")->field("p_name,p_id")->select();
        foreach ($payments as $pv) {
            $pay_type[$pv["p_id"]] = $pv["p_name"];
        }
        // 配送方式
        $expres = M("express")->field("e_name,id")->select();
        foreach ($expres as $ev) {
            $send_type[$ev["id"]] = $ev["e_name"];
        }
        //查询发货人的姓名
        $agent_name = M('agent')->where( array('agent_id'=>$order['deliver_person']) )->getField('agent_name');
        // 收货人地址
        $address = M("agent_address")->where("address_id = %d" ,array($order['address_id']))->find();


        $this->assign('pay_type', $pay_type);
        $this->assign('send_type', $send_type);
        $this->assign('address', $address);
        $this->assign('sum', $sum);
        $this->assign('agent_name', $agent_name);
        $this->assign('orderThrough', $orderThrough);
        $this->assign('orderGood',$orderGood);
        $this->assign('orderGood',$orderGood);
        $this->assign('order',$order);
        $this->assign('brand',$brand);
        $this->assign('brand_name',$brand_name);
        $this->assign('brand_money',$brand_money);
        $this->display();
    }

    //上级代理本人发货
    public function my_deliver() {
        //把订单的发货状态改为1和写入发货人
        $uid = session('user_id');
        $order_id = I('post.order_id');
        $price_sum = I('post.price_sum');
        $bool = M('order')->where( array('id'=>$order_id) )->save( array('is_deliver'=>1, 'deliver_person'=>$uid,'deliver_time' => time()) );
        //把订单流程表的state改为1
        M('orderThrough')->where( array('uid'=>$uid, 'order_id'=>$order_id) )->save( array('state'=>1, 'is_deliver'=>1, 'price'=>$price_sum) );
        //写入快递号
        $code_num = I('post.code_num');
        M('order')->where( array('id'=>$order_id) )->save( array('code_num'=>$code_num) );
        $this->ajaxReturn($bool);
    }

    //确认收货并返利
    public function confirm_good() {
        //把订单状态改为已完成
        $order_id = I('post.order_id');
        // 验证订单
        $order = M('order')->where("uid = %d AND id = %d" ,array(session("user_id") ,$order_id))->find();
        if($order["is_pay"] != 1 || $order["is_deliver"] != 1) {
            $this->ajaxReturn(array("status" => "error" ,"msg" => "订单信息有误"));
        }
        M('order')->where( array('id'=>$order_id) )->save( array('status'=>3) );

        //计算业绩
        $all_chi = M('agent')->where( array('agent_id'=>$order['uid']) )->getField('all_achi');
        $new_all_chi = $order['price'] + $all_chi;
        M('agent')->where( array('agent_id'=>$order['uid']) )->save( array('all_achi'=>$new_all_chi) );
        $this->ajaxReturn(array("status" => "success"));
    }

    //加载更多的商品
    public function more()
    {
        //过滤条件
        $num = (I('post.page') - 1)*3;
        $state = I('post.state');
        $uid = session('user_id');
        $map['uid'] = $uid;

        switch($state){
            case "ncheck" :
                $map2['a.uid'] = $uid;
                break;
            case "npay" :
                $map['is_pay'] = array('eq', -1);
                $map['status'] = array('neq', -1);
                break; // 待付款
            case "is_d" :
                $map['is_deliver'] = 1;
                $map['status'] = array('neq' ,3);
                break;// 已发货
            case "to_d" :
                $map['is_pay'] = 1;
                $map['is_deliver'] = -1;
                break; // 已支付
            default : ;break;
        }
        $search = trim(I('post.search'));
        if ( !empty($search) ) {
            ($state == 'ncheck') ? $map2['b.order_id'] = $search : $map['order_id'] = $search;
        }
        if ($state == 'ncheck') {//审核
            $order = D('Admin/Order')->orderGoodThrough($map2,"$num,3");
        } else {//全部,待付款,待发货,待收货
            $order = D('Admin/Order')->orderGood($map,"$num,3");
        }

        if (empty($order)) {
            echo 1;
        } else {
            $this->assign('order', $order);
            $this->display();
        }
    }

    //取消订单
    public function cancel()
    {
        $order_id = I('post.order_id');
        $where["id"] = $order_id;
        $where["is_pay"] = -1;
        $bool = M('order')->where($where)->save( array('status' => -1) );
        $this->ajaxReturn($bool);
    }

    //提交订单
    public function place() {

        $uid = session('user_id');
        $good_id = I('post.good_id');
        $message = I('post.message');
        $address_id = I('post.address_id');
        $good_type = I('post.good_type');
        $number = I('post.num');
        //连运费的总价
        $price = I('post.price');
        $freight_price = I('post.freight_price');
        $pay_type = to_int(I('post.pay_type'));
        $send_type = to_int(I('post.send_type'));

        $good_idaarry = explode(",",$good_id);
        $good_numarray = explode(",",$number);
        $good_statusarray = explode(",",$good_type);
        //先查询是否有收货地址，没有的话没法提交
        $agentAddress = M('agentAddress')->where( array('agent_id' => $uid) )->find();
        if (empty($agentAddress)) {
            $this->ajaxReturn(-2);
        }
        $is_agent = M('agent')->where(array('agent_id'=>session('user_id')))->getField('is_agent');
        //计算订单总价格（没考虑到没代理此品牌的商品）
        foreach($good_idaarry as $key => $value) {
            $good = M('good')->where(array('id' => $value))->find();
            $num = $good_numarray[$key];
            $num = intval($num);
            if ($num == 0) {
                $num = $num + 1;
            }
            if($is_agent == 2){
                //如果是普通用户
                $total = $good['price'] * $num;
            }else{
                //如果是代理的话
                $agent_brand = M("brand")->where("id = %d", array($good['brand_id']))->getField("agent_brand");
                if ($agent_brand == 1) {//代理商品
                    //没代理此商品的品牌
                    $bool = M('agentBrand')->where(array('agent_id' => $uid, 'brand_id' => $good['brand_id']))->find();
                    if (empty($bool)) {
                        $total = $good['price'] * $num;
                    } else {
                        $good_type = $good_statusarray[$key];
                        $rank_id = M('agentBrand')->where(array('agent_id' => $uid, 'brand_id' => $good['brand_id']))->getField('rank_id');
                        $goodRankPrice = M('goodRankPrice')->where(array('good_id' => $value, 'rank_id' => $rank_id))->find();
                        //$good_type=1 单件   $good_type=2 整箱
                        $total = ($good_type == 1) ? $goodRankPrice['unit_amt'] * $num : $goodRankPrice['batch_amt'] * $num;
                    }
                } else {//商家商品
                    $total = $good['price'] * $num;
                }
            }
            $sum[] = $total;
        }
        $goods_count_amt = array_sum($sum);
        // 计算出总价加上支付费用
        $pay_fee = M("payment")->where("p_id = %d",array($pay_type))->getField("p_fee");
        $pay_amt = round(($pay_fee * $goods_count_amt) / 100 ,2); // 商品支付费用
        $allsum = $goods_count_amt + $freight_price + $pay_amt; // 支付总费用
        //验证算出来的总价与上传的总价是否一致
        if($allsum != $price){
            $this->ajaxReturn(-1);
        }
        //获取收货地址
        $detail_address = M('agentAddress')->where( array('address_id'=>to_int(I('post.address_id'))) )->find();
        //下单人的手机号码
        $user_phone = M('agent')->where( array('agent_id'=>$uid) )->getField('mobile');
        //插入到订单表
        $data = array(
            'order_id' => get_order_id(),
            'uid' => $uid,
            'address_id' => to_int($address_id),
            'time' => time(),
            'message' => $message,
            'price' => $price,
            'user_phone' => $user_phone,
            'detail_area'=>$detail_address['province'].$detail_address['city'].$detail_address['area'].$detail_address['detail_address'],
            'consignee' =>$detail_address['consignee'],
            'phone' => $detail_address['mobile'],
            'freight_price' => to_int($freight_price),
            'pay_type' => $pay_type,
            'send_type' => $send_type,
            'service_price' => $pay_amt
        );
        $id = M('order')->add($data);


        //订单和商品的关系
        foreach($good_idaarry as $gey=>$val) {
            $goods_price = D('Admin/Good')->goodPrice($val,$good_numarray[$gey],$good_statusarray[$gey]);
            $res = array(
                'order_id' => $id,
                'good_id' => $val,
                'num' => $good_numarray[$gey],
                'good_type' => $good_statusarray[$gey],
                'goods_price' => $goods_price
            );
            M('orderGood')->add($res);
        }

        //连接redis把购物车的数据取出来
        $redis = new \Redis();
        $redis->connect('119.23.24.184', 6379);
        $redis->auth("123456");
        $res = $redis->get(session('user_id') . "_shoplist");
        $shopcart = json_decode($res, true);
        //删除购物车数据，保存
        $good_aid = I('post.good_aid');
        $good_aidarray = explode(",",$good_aid);
        foreach ($good_aidarray as $ley=>$vall){
            unset($shopcart[$vall]);
            M('shop_cart')->where(array('agent_id'=>session('user_id'),'cart_id'=>$vall))->delete();
        }
        $redis->set(session('user_id')."_shoplist",json_encode($shopcart));

        //下单把订单推送上级(如果没有上级,把订单推送给订单对应的的商品的任意1个品牌的最顶级代理)
        $self = M('agent')->where( array('agent_id'=>$uid) )->find();
        //不是代理的话，平台发货
        if($self["is_agent"] == 1){ // 是代理才会存在订单推送的情况
            if ($self['parent_id'] != 0) {// 有上级
                $data = array(
                    'order_id' => $id,
                    'uid' => $self['parent_id'],
                    'state' => 0,
                    'price' => top_order_price($id, $self['parent_id'])
                );
                M('orderThrough')->add($data);
            } else {
                if (!_is_director()) {//没上级,不是董事
                    $brand_id = M('good')->where( array('id'=>$good_idaarry[0]) )->getField('brand_id');
                    $top_agent = top_rank($brand_id);
                    //不存在董事
                    if(!$top_agent){
                        M('order')->where( array('id'=>$id) )->save( array('is_platform'=>1) );
                    }else{
                        $data = array(
                            'order_id' => $id,
                            'uid' => $top_agent['agent_id'],
                            'state' => 0,
                            'price' => top_order_price($id, $top_agent['agent_id'])
                        );
                        M('orderThrough')->add($data);
                    }
                } else {// 没上级,董事
                    M('order')->where( array('id'=>$id) )->save( array('is_platform'=>1) );
                }
            }
        } else {
            M('order')->where( array('id'=>$id) )->save( array('is_platform'=>1) );
        }
        $this->ajaxReturn($id);
    }

    //推送订单给上一级
    public function confirm() {

        //订单id和用户id
        $iid = I('post.iid');
        $uid = session('user_id');

        //推送给上一级需要扣自己的余额
        $order_price = top_order_price($iid, $uid);
        $money = M('agent')->where( array('agent_id'=>$uid) )->getField('money');
        $freight_price = M('order')->where( array('id'=>$iid) )->getField('freight_price');
        $flag = $money - $order_price - $freight_price;// 上级代理订单总价格=订单本身的总价格($order_price)+下单人的运费($freight_price)
        if ($flag < 0) {//余额不足，返回-1
            $this->ajaxReturn(-1);
        } else {//扣余额
            M('agent')->where( array('agent_id'=>$uid) )->save( array('money'=>$flag) );
        }
        //推送给上级的时候,把记录的state改为1,代表已经审核过了
        M('orderThrough')->where( array('order_id'=>$iid, 'uid'=>$uid) )->save( array('state' => 1) );
        //生成给上一级的订单审核
        $parent_id = M('agent')->where( array('agent_id'=>$uid) )->getField('parent_id');
        if (!_is_director()) {//非顶层代理推送到上级的时候,生成记录
            $data = array(
                'uid' => $parent_id,
                'state' => 0,
                'order_id' => $iid,
                'is_deliver' => 0,
                'price' => top_order_price($iid,$parent_id),//上级代理订单的金额(不包括运费和折扣)
            );
            //设置此代理订单的总价格
            M('orderThrough')->add($data);
        } else {//当最顶级代理提交到平台的话，把is_platform改为1,代表需要平台发货
            M('order')->where( array('id'=>$iid) )->save( array('is_platform'=>1) );
        }
        $this->ajaxReturn(1);//成功返回1
    }

    // 计算订单支付手续费
    public function sum_pay_fee()
    {
        if(IS_AJAX){
            $pay_type = to_int(I("post.pay_type"));
            $pay_amt = to_int(I("post.pay_amt"));
            $pay_fee = M("payment")->where("p_id = %d",array($pay_type))->getField("p_fee");
            $amt = round(($pay_fee * $pay_amt) / 100 ,2);
            $this->ajaxReturn(array("amt" => $amt));
        }else{
            exit("error");
        }
    }
}